/*
 * Copyright (C) 2010 by CODEBISTRO LLC.
 *
 * The license is granted to use, reproduce, modify, display, perform, sublicense
 * and distribute this code under the conditions of the Mozilla Public License v 1.1.
 *
 * The text of the license is available with this source as MPL-1.1.txt
 * or at http://www.mozilla.org/MPL/MPL-1.1.txt.
 */

package org.codebistro.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;

public class Classes  {
    /**
     * @param className -
     *            fully qualified class name
     * @return resource path of the class file
     */
    public static String class2ResourceName(String className) {
        return "/" + className.replace('.', '/') + ".class";
    }

    public static URL getOwnerJar(final URL resourceUrl) {
        if (!"jar".equals(resourceUrl.getProtocol()))
            throw new Bark("Resource '" + resourceUrl + "' not packaged in JAR");

        String filePart= resourceUrl.getPath();

        int indexOfSeparator= filePart.indexOf('!');
        if (indexOfSeparator >= 0) {
            filePart= filePart.substring(0, indexOfSeparator);
        }

        try {
            return new URL(filePart);
        } catch (MalformedURLException e) {
            throw Bark.unchecker(e);
        }
    }

    public static URL getOwnerJar(final String resourcePath) {
        final URL resourceUrl= Classes.class.getResource(resourcePath);

        if (!"jar".equals(resourceUrl.getProtocol())) {
            return null;
        }

        return getOwnerJar(resourceUrl);
    }


}
